package com.yinhai.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cmcc.groupcontacts.MainApp;
import com.listener.MsgTextLongClickListener;
import com.littlec.sdk.business.MessageConstants;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.entity.CMMessage;
import com.littlec.sdk.entity.messagebody.AudioMessageBody;
import com.littlec.sdk.entity.messagebody.ImageMessageBody;
import com.littlec.sdk.entity.messagebody.LocationMessageBody;
import com.littlec.sdk.entity.messagebody.TextMessageBody;
import com.littlec.sdk.manager.CMIMHelper;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener.CMCallBack;
import com.lz.util.Utils;
import com.yinhai.adapter.PlusAdpter;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.ChatConstant;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.custom.RecordButton;
import com.yinhai.custom.RecordButton.OnFinishedRecordListener;
import com.yinhai.model.ChatMsgEntity;
import com.yinhai.model.ChatMsgViewAdapter;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.Expressions;
import com.yinhai.model.MsgModel;
import com.yinhai.photo.utils.Photo;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.service.MsgServiceImpl;
import com.yinhai.util.GetTimeLength;
import com.yinhai.util.NullUtils;
import com.yinhai.util.PhoneNameMapUtil;
import com.yinhai.util.Util;
import com.yinhai.view.DialogFactory;
import com.yinhai.view.MsgEditText;

/**
 * 即时通讯
 * 
 * @author lixh
 * 
 */
public class ChatActivity extends Activity implements OnClickListener {
    // 列表项弹出窗口
    // private static PopupWindow mPdw_nav = null;
    private Context context;
    
    private ImageView im_btn_call;
    
    private MsgServiceImpl msgService;
    
    // 向个人发送消息
    AsyncTaskParam sendSingleContentsParam = new AsyncTaskParam(UrlConstant.CONTACT_USER_URI
        + UrlConstant.SEND_SINGLE_CONTENTS);
    
    // 向群组发送消息
    AsyncTaskParam sendGroupContentsParam = new AsyncTaskParam(UrlConstant.CONTACT_USER_URI
        + UrlConstant.SEND_GROUP_CONTENTS);
    
    // 接收指定用户发送的消息
    AsyncTaskParam recSingleContentsParam = new AsyncTaskParam(UrlConstant.CONTACT_USER_URI
        + UrlConstant.RCV_SINGLECONTENT_FROM_SENDUID);
    
    // 接收群组发的消息
    AsyncTaskParam recGroupContentsParam = new AsyncTaskParam(UrlConstant.CONTACT_USER_URI
        + UrlConstant.RCV_GROUPCONTENT_FROM_SENDUID);
    
    private ViewPager viewPager;
    
    private ArrayList<GridView> grids;
    
    private int[] expressionImages;
    
    private String[] expressionImageNames;
    
    private int[] expressionImages1;
    
    private String[] expressionImageNames1;
    
    private int[] expressionImages2;
    
    private String[] expressionImageNames2;
    
    private Button mBtnSend;// 发送文本
    
    private ImageView mBtnBack;
    
    private Bitmap bitmap;// 选择的图片
    
    private ImageButton voiceBtn;
    
    private ImageButton keyboardBtn;
    
    private ImageButton biaoqingBtn;
    
    private ImageButton biaoqingfocuseBtn;
    
    private ImageButton plusBtn;
    
    private LinearLayout ll_fasong;
    
    private LinearLayout ll_yuyin;
    
    private RecordButton btn_yuyin;// 录音按钮
    
    View softkeybroadview;
    
    // 录音的根路径
    // private String path = Environment.getExternalStorageDirectory()
    // .getAbsolutePath();
    private LinearLayout page_select;
    
    private ImageView page0;
    
    private ImageView page1;
    
    private ImageView page2;
    
    private MsgEditText mEditTextContent;
    
    private ListView mListView;
    
    private GridView gView1;
    
    private GridView gView2;
    
    private GridView gView3;
    
    private ChatMsgViewAdapter mAdapter;
    
    private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
    
    private String sendID;// 发送者ID 就是自己
    
    private String sendName;// 发送者名字,自己名字
    
    private String receID;// 接受者ID 聊天的对象
    
    private String receName;
    
    private int type;
    
    private boolean isGroup = false;
    
    private String groupId;// 群组ID
    
    private String groupName;// 群组名称
    
    private String isreceipt = "0"; // 0, 未送达 1 ，送达
    
    SpannableString spannablepic;
    
    private GridView plusGV;
    
    private PlusAdpter plusAdapter;
    
    private ContactsUser receContactUser;
    
    private ContactUserServiceImpl contactUserServiceImpl;
    
    MsgModel resendMsgModel;
    
    private Dialog conferenceConfirmDialog;
    
    ProgressDialog loadMask = null;
    private Uri photoUri = null;
    private String photoUUid = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_xiaohei);
        if (getIntent().hasExtra(MsgTextLongClickListener.SER_KEY)) {
            resendMsgModel = (MsgModel)getIntent().getSerializableExtra(MsgTextLongClickListener.SER_KEY);
        }
        context = ChatActivity.this;
       
        // 注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.im.message");
        intentFilter.addAction("com.im.messageresver");
        intentFilter.addAction("com.im.sendpos");
        intentFilter.addAction("com.im.delmessage");
        registerReceiver(receiver, intentFilter);
        registerReceiver(chatnavreceiver, new IntentFilter("com.im.chatnavreceiver"));
        
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        contactUserServiceImpl = new ContactUserServiceImpl(this);
        msgService = new MsgServiceImpl(this);
        LoginConfig config = LoginConfigUtil.getConfig(this);
        sendID = config.getUsername();
        sendName = PhoneNameMapUtil.findName(sendID, context);
        ContactsUser contactsUser = contactUserServiceImpl
				.findOnlineContactsUserByIMUserName(sendID);
        if(contactsUser != null) {
        	 sendName = contactsUser.getName() == null?"":contactsUser.getName();
        	 CMChatGlobalStorage.getInstance().setmLoginUserRealName(sendName);
        }
       
        receName = getIntent().getStringExtra("receName");
        receID = getIntent().getStringExtra("receID");
        groupId = getIntent().getStringExtra("groupId") == null ? "" : getIntent().getStringExtra("groupId");
        groupName = getIntent().getStringExtra("groupName") == null ? "" : getIntent().getStringExtra("groupName");
        type = getIntent().getIntExtra("type", 1);
        if (receID == null) {
            finish();
            return;
        }
        
        im_btn_call = (ImageView)findViewById(R.id.btn_call);
        im_btn_call.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // if (type == 1) {
                // if (receContactUser != null) {
                // Intent intent = new Intent(ChatActivity.this, CallActivity.class);
                // VOIPPhoneRecord record = new VOIPPhoneRecord();
                // record.setContactname(receContactUser.getName());
                // record.setState(1);
                // record.setTelnum(receContactUser.getTelPhone());
                // record.setUserName(receContactUser.getImUserName());
                //
                // intent.putExtra("data", record);
                // intent.putExtra("pickup", false);
                // startActivity(intent);
                // }
                // } else {
                // showCreateConferenceConfirmDialog();
                // }
                if (type == 1) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + receID));
                    
                    ChatActivity.this.startActivity(intent);
                }
            }
        });
        
        // 一对一聊天
        if (type == 1) {
            im_btn_call.setVisibility(View.VISIBLE);
            List<ContactsUser> contactUsers = contactUserServiceImpl.findOnlineContactsUserByPhone(receID);
            if (NullUtils.isNotEmpty(contactUsers)) {
                receContactUser = contactUsers.get(0);
            }
            
            if (receContactUser == null) {
                Util.showMsg(this, "在通讯录未找到联系人，请同步通讯录");
                finish();
                return;
            }
            if (NullUtils.isEmpty(receContactUser.getImUserName())) {
                Util.showMsg(this, "通讯录信息丢失，缺少即时通讯帐号，请同步通讯录");
                finish();
                return;
            }
        }
        
        // 群聊
        if (type > 1) {
            isGroup = true;
            
            if (im_btn_call.getVisibility() != View.GONE) {
                im_btn_call.setVisibility(View.GONE);
            }
            findViewById(R.id.btn_group_user).setVisibility(View.VISIBLE);
        }
        
        TextView textView = (TextView)this.findViewById(R.id.tvtest);
        textView.setText(receName);
        
        ll_fasong = (LinearLayout)this.findViewById(R.id.ll_fasong);
        ll_yuyin = (LinearLayout)this.findViewById(R.id.ll_yuyin);
        btn_yuyin = (RecordButton)ll_yuyin.findViewById(R.id.btn_yuyin);
        page_select = (LinearLayout)this.findViewById(R.id.page_select);
        page0 = (ImageView)this.findViewById(R.id.page0_select);
        page1 = (ImageView)this.findViewById(R.id.page1_select);
        page2 = (ImageView)this.findViewById(R.id.page2_select);
        mListView = (ListView)this.findViewById(R.id.listview);
        expressionImages = Expressions.expressionImgs;
        expressionImageNames = Expressions.expressionImgNames;
        expressionImages1 = Expressions.expressionImgs1;
        expressionImageNames1 = Expressions.expressionImgNames1;
        expressionImages2 = Expressions.expressionImgs2;
        expressionImageNames2 = Expressions.expressionImgNames2;
        viewPager = (ViewPager)this.findViewById(R.id.viewpager);
        mBtnSend = (Button)this.findViewById(R.id.btn_send);
        mBtnSend.setOnClickListener(this);
        
        mBtnBack = (ImageView)this.findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(this);
        voiceBtn = (ImageButton)this.findViewById(R.id.chatting_voice_btn);
        voiceBtn.setOnClickListener(this);
        keyboardBtn = (ImageButton)this.findViewById(R.id.chatting_keyboard_btn);
        keyboardBtn.setOnClickListener(this);
        biaoqingBtn = (ImageButton)this.findViewById(R.id.chatting_biaoqing_btn);
        biaoqingBtn.setOnClickListener(this);
        biaoqingfocuseBtn = (ImageButton)this.findViewById(R.id.chatting_biaoqing_focuse_btn);
        biaoqingfocuseBtn.setOnClickListener(this);
        mEditTextContent = (MsgEditText)this.findViewById(R.id.et_sendmessage);
        plusBtn = (ImageButton)this.findViewById(R.id.chatting_plus_focuse_btn);
        plusBtn.setOnClickListener(this);
        
        plusGV = (GridView)this.findViewById(R.id.plus_gridview);
        
        mEditTextContent.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
                if (s.length() > 0) {
                    mBtnSend.setVisibility(View.VISIBLE);
                    plusBtn.setVisibility(View.GONE);
                    
                }
                else if (s.length() == 0) {
                    mBtnSend.setVisibility(View.GONE);
                    plusBtn.setVisibility(View.VISIBLE);
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }
            
            @Override
            public void afterTextChanged(Editable s) {
                
            }
        });
        
        btn_yuyin.setOnFinishedRecordListener(new OnFinishedRecordListener() {
            
            @Override
            public void onFinishedRecord(String audioPath) {
                try {
                    
                    String fileName = btn_yuyin.getmFileName();
                    
                    String uuid = UUID.randomUUID().toString();
                    MsgModel msgModel = new MsgModel();
                    msgModel.setUuid(uuid);
                    msgModel.setContent(fileName);
                    ;
                    msgModel.setFileName(fileName);
                    // 语音
                    msgModel.setConType(Contact.REDIO + "");
                    msgModel.setRecId(receID);
                    msgModel.setRecName(receName);
                    msgModel.setSendDate(getDate());
                    msgModel.setSendUserId(sendID);
                    msgModel.setSendUserName(sendName);
                    msgModel.setSecond(String.valueOf(btn_yuyin.getTime()));
                    if (type > 1 ? true : false) {
                        msgModel.setIsGroup("1");
                    }
                    else {
                        msgModel.setIsGroup("0");// 个人聊天
                        // msgModel.setIsreceipt(isreceipt);
                    }
                    if (type > 1) {
                        msgModel.setGroupId(groupId);
                        msgModel.setGroupName(groupName);
                    }
                    msgModel.setIsreceipt("0");
                    msgService.saveIM(msgModel);
                    sendMessage(Contact.REDIO, msgModel, uuid);
                    ChatMsgEntity entity = new ChatMsgEntity();
                    entity.setMsgModel(msgModel);
                    entity.setUuid(uuid);
                    entity.setDate(getDate());
                    entity.setName(sendName);
                    entity.setMsgType(false);
                    entity.setText("");
                    entity.setType(Contact.REDIO + "");
                    entity.setFileName(fileName);
                    entity.setIsreceipt(isreceipt);
                    Bitmap bitmap1 = null;
                    Drawable d = getResources().getDrawable(R.drawable.me_dis_read);
                    // xxx根据自己的情况获取drawable
                    BitmapDrawable bd = (BitmapDrawable)d;
                    bitmap1 = bd.getBitmap();
                    ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap1);
                    String yy_str = "a  " + GetTimeLength.getTimeLength(String.valueOf(btn_yuyin.getTime()));
                    spannablepic = new SpannableString(yy_str);
                    spannablepic.setSpan(new ForegroundColorSpan(Color.LTGRAY),
                        3,
                        yy_str.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannablepic.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
                        3,
                        yy_str.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannablepic.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    
                    entity.setSpStr(spannablepic);
                    mDataArrays.add(entity);
                    mEditTextContent.setText("");
                    viewPager.setVisibility(ViewPager.GONE);
                    page_select.setVisibility(View.GONE);
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(mListView.getCount() - 1);
                    mEditTextContent.requestFocus(); // 请求获取焦点
                    mEditTextContent.clearFocus();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 录音事件 end
        initViewPager();
        initData();
    }
    
    /**
     * 更多功能点击事件
     */
    private OnItemClickListener plusItemClickListener = new OnItemClickListener() {
        
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
                case 0:
                    // 图片
                    /*
                     * albumLinearLayout.setVisibility(View.VISIBLE); aibumGV.setVisibility(View.GONE);
                     * photoGV.setVisibility(View.VISIBLE);
                     * 
                     * adapter = new PhotoAdappter(ChatActivity.this, aibum); photoGV.setAdapter(adapter);
                     * photoGV.setOnItemClickListener(gvItemClickListener);
                     */
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 2);
                    break;
                case 1:
                    /**
                     * 拍照
                     */
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, getPhotoUri());
                    startActivityForResult(intent, 1);
                    
                    break;
                case 2:
                    // 定位
                    String uuid = UUID.randomUUID().toString();
                    Intent it = new Intent(ChatActivity.this, PosLocation.class);
                    it.putExtra("uuid", uuid);
                    startActivity(it);
                    break;
            
            }
        }
    };
    
    private Uri getPhotoUri() {
    	photoUUid = UUID.randomUUID().toString();
    	photoUri = Uri.fromFile(new File(Photo.getSaveIMPicPath(),  photoUUid+ ".jpg"));
    	return photoUri;
    }
    
    private void initViewPager() {
        LayoutInflater inflater = LayoutInflater.from(this);
        grids = new ArrayList<GridView>();
        gView1 = (GridView)inflater.inflate(R.layout.grid1, null);
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 24; i++) {
            Map<String, Object> listItem = new HashMap<String, Object>();
            listItem.put("image", expressionImages[i]);
            listItems.add(listItem);
        }
        
        SimpleAdapter simpleAdapter =
            new SimpleAdapter(this, listItems, R.layout.singleexpression, new String[] {"image"},
                new int[] {R.id.image});
        gView1.setAdapter(simpleAdapter);
        gView1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeResource(getResources(), expressionImages[arg2 % expressionImages.length]);
                ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);
                SpannableString spannableString =
                    new SpannableString(
                        expressionImageNames[arg2].substring(1, expressionImageNames[arg2].length() - 1));
                spannableString.setSpan(imageSpan,
                    0,
                    expressionImageNames[arg2].length() - 2,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mEditTextContent.append(spannableString);
            }
        });
        grids.add(gView1);
        
        gView2 = (GridView)inflater.inflate(R.layout.grid2, null);
        grids.add(gView2);
        
        gView3 = (GridView)inflater.inflate(R.layout.grid3, null);
        grids.add(gView3);
        
        PagerAdapter mPagerAdapter = new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }
            
            @Override
            public int getCount() {
                return grids.size();
            }
            
            @Override
            public void destroyItem(View container, int position, Object object) {
                ((ViewPager)container).removeView(grids.get(position));
            }
            
            @Override
            public Object instantiateItem(View container, int position) {
                ((ViewPager)container).addView(grids.get(position));
                return grids.get(position);
            }
        };
        
        viewPager.setAdapter(mPagerAdapter);
        
        viewPager.setOnPageChangeListener(new GuidePageChangeListener());
    }
    
    private void initData() {
        if (resendMsgModel != null) {
            if (Contact.TEXT == Integer.valueOf(resendMsgModel.getConType())) {
                String uuid = UUID.randomUUID().toString();
                MsgModel msgModel = new MsgModel();
                msgModel.setUuid(uuid);
                msgModel.setContent(resendMsgModel.getContent());
                // 文字类型
                msgModel.setConType(Contact.TEXT + "");
                msgModel.setRecId(receID);
                msgModel.setRecName(receName);
                msgModel.setSendDate(getDate());
                msgModel.setSendUserId(sendID);
                msgModel.setSendUserName(this.sendName);
                if (this.isGroup) {
                    msgModel.setIsGroup("1");
                }
                else {
                    msgModel.setIsGroup("0");// 个人聊天
                }
                if (type > 1) {
                    msgModel.setGroupId(groupId);
                    msgModel.setGroupName(groupName);
                }
                msgModel.setIsreceipt("0");
                try {
                    msgService.saveIM(msgModel);
                    sendMessage(Contact.TEXT, resendMsgModel, uuid);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (Contact.PHOTO == Integer.valueOf(resendMsgModel.getConType())) {
                String uuid = UUID.randomUUID().toString();
                final MsgModel msgModel = new MsgModel();
                msgModel.setUuid(uuid);
                // 文字类型
                msgModel.setConType(Contact.PHOTO + "");
                msgModel.setRecId(receID);
                msgModel.setRecName(receName);
                msgModel.setSendDate(getDate());
                msgModel.setSendUserId(sendID);
                msgModel.setSendUserName(this.sendName);
                msgModel.setIsreceipt(isreceipt);
                if (this.isGroup) {
                    msgModel.setIsGroup("1");
                }
                else {
                    msgModel.setIsGroup("0");// 个人聊天
                }
                if (type > 1) {
                    msgModel.setGroupId(groupId);
                    msgModel.setGroupName(groupName);
                }
                
                File file = new File(Photo.getSaveIMPicPath() + resendMsgModel.getUuid() + ".png");
                if (file.exists()) {
                    msgModel.setFileName(file.getPath());
                    msgService.saveIM(msgModel);
                    sendMessage(Contact.PHOTO, msgModel, uuid);
                }
                else {
                    if (loadMask != null && loadMask.isShowing()) {
                        loadMask.dismiss();
                    }
                    loadMask = ProgressDialog.show(context, null, "图片资源下载中，请稍等....");
                    loadMask.setCancelable(true);
                    loadMask.show();
                    AQuery query = new AQuery(this);
                    query.download(resendMsgModel.getFileName(), new File(Photo.getSaveIMPicPath() + msgModel.getUuid()
                        + ".png"), new AjaxCallback<File>() {
                        
                        @Override
                        public void callback(String url, File file, AjaxStatus status) {
                            super.callback(url, file, status);
                            if (file != null && file.exists()) {
                                msgModel.setFileName(file.getPath());
                                msgService.saveIM(msgModel);
                                
                                ChatMsgEntity entity = new ChatMsgEntity();
                                entity.setMsgModel(msgModel);
                                entity.setUuid(msgModel.getUuid());
                                entity.setDate(getDate());
                                entity.setName(sendName);
                                entity.setMsgType(false);
                                entity.setText(file.getPath());
                                entity.setIsreceipt("0");
                                entity.setType(msgModel.getConType());
                                mDataArrays.add(entity);
                                mAdapter.notifyDataSetChanged();
                                sendMessage(Contact.PHOTO, msgModel, msgModel.getUuid());
                            }
                            if (loadMask != null && loadMask.isShowing()) {
                                loadMask.dismiss();
                            }
                        }
                        
                    });
                    
                }
            }
            else if (Contact.POSMAP == Integer.valueOf(resendMsgModel.getConType())) {
                String uuid = UUID.randomUUID().toString();
                final MsgModel msgModel = new MsgModel();
                msgModel.setUuid(uuid);
                msgModel.setContent(resendMsgModel.getContent());
                // 文字类型
                msgModel.setConType(Contact.POSMAP + "");
                msgModel.setRecId(receID);
                msgModel.setRecName(receName);
                msgModel.setSendDate(getDate());
                msgModel.setSendUserId(sendID);
                msgModel.setSendUserName(this.sendName);
                msgModel.setLatitude(resendMsgModel.getLatitude());
                msgModel.setLongitude(resendMsgModel.getLongitude());
                if (this.isGroup) {
                    msgModel.setIsGroup("1");
                }
                else {
                    msgModel.setIsGroup("0");// 个人聊天
                }
                if (type > 1) {
                    msgModel.setGroupId(groupId);
                    msgModel.setGroupName(groupName);
                }
                msgModel.setIsreceipt("0");
                File file = new File(Photo.getSaveIMPicPath() + resendMsgModel.getUuid() + ".png");
                if (file.exists()) {
                    msgModel.setFileName(file.getPath());
                    msgService.saveIM(msgModel);
                    sendMessage(Contact.PHOTO, msgModel, uuid);
                }
                else {
                    if (loadMask != null && loadMask.isShowing()) {
                        loadMask.dismiss();
                    }
                    loadMask = ProgressDialog.show(context, null, "位置图片资源下载中，请稍等....");
                    loadMask.setCancelable(true);
                    loadMask.show();
                    AQuery query = new AQuery(this);
                    query.download(resendMsgModel.getFileName(), new File(Photo.getSaveIMPicPath() + msgModel.getUuid()
                        + ".png"), new AjaxCallback<File>() {
                        
                        @Override
                        public void callback(String url, File file, AjaxStatus status) {
                            super.callback(url, file, status);
                            if (file != null && file.exists()) {
                                msgModel.setFileName(file.getPath());
                                msgService.saveIM(msgModel);
                                
                                ChatMsgEntity entity = new ChatMsgEntity();
                                entity.setMsgModel(msgModel);
                                entity.setUuid(msgModel.getUuid());
                                entity.setDate(getDate());
                                entity.setName(sendName);
                                entity.setMsgType(false);
                                entity.setText(file.getPath());
                                entity.setIsreceipt("0");
                                entity.setType(msgModel.getConType());
                                mDataArrays.add(entity);
                                mAdapter.notifyDataSetChanged();
                                
                                sendMessage(Contact.PHOTO, msgModel, msgModel.getUuid());
                            }
                            if (loadMask != null && loadMask.isShowing()) {
                                loadMask.dismiss();
                            }
                        }
                        
                    });
                }
            }
        }
        mDataArrays.addAll(msgService.findSimgleMessage(sendID, this.receID, this.isGroup));
        mAdapter = new ChatMsgViewAdapter(this, mDataArrays, isGroup);
        mListView.setAdapter(mAdapter);
    }
    
    private String getDate() {
        Calendar c = Calendar.getInstance();
        String year = String.valueOf(c.get(Calendar.YEAR));
        int month = (c.get(Calendar.MONTH) + 1);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int mins = c.get(Calendar.MINUTE);
        int sec = c.get(Calendar.SECOND);
        
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + " "
            + (hour < 10 ? "0" + hour : hour) + ":" + (mins < 10 ? "0" + mins : mins) + ":"
            + (sec < 10 ? "0" + sec : sec));
        return sbBuffer.toString();
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                ChatConstant.CURRENT_CHAT = "";
                ChatConstant.CURRENT_CHART_ID = "";
                onBackPressed();
                break;
            case R.id.btn_send:
                String content = mEditTextContent.getText().toString();
                if (content.length() > 0) {
                    
                    // 编辑框内容不为空时点发送按钮关闭软键盘
                    softkeybroadview = getWindow().peekDecorView();
                    if (softkeybroadview != null) {
                        InputMethodManager inputmanger =
                            (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputmanger.hideSoftInputFromWindow(softkeybroadview.getWindowToken(), 0);
                    }
                    
                    voiceBtn.setVisibility(View.VISIBLE);
                    biaoqingBtn.setVisibility(View.VISIBLE);
                    biaoqingfocuseBtn.setVisibility(View.GONE);
                    viewPager.setVisibility(View.GONE);
                    page_select.setVisibility(View.GONE);
                    keyboardBtn.setVisibility(View.GONE);
                    ll_fasong.setVisibility(View.VISIBLE);
                    ll_yuyin.setVisibility(View.GONE);
                    plusGV.setVisibility(View.GONE);
                    
                    // sendMessage(this.isGroup, content, Contact.TEXT);
                    String uuid = UUID.randomUUID().toString();
                    
                    MsgModel msgModel = new MsgModel();
                    msgModel.setUuid(uuid);
                    msgModel.setContent(content);
                    // 文字类型
                    msgModel.setConType(Contact.TEXT + "");
                    msgModel.setRecId(receID);
                    msgModel.setRecName(receName);
                    msgModel.setSendDate(getDate());
                    msgModel.setSendUserId(sendID);
                    msgModel.setIsreceipt(isreceipt);
                    msgModel.setSendUserName(this.sendName);
                    if (this.isGroup) {
                        msgModel.setIsGroup("1");
                    }
                    else {
                        msgModel.setIsGroup("0");// 个人聊天
                    }
                    if (type > 1) {
                        msgModel.setGroupId(groupId);
                        msgModel.setGroupName(groupName);
                    }
                    try {
                        msgService.saveIM(msgModel);
                        msgModel.setContent(Expressions.SendTxtMsgTranslate(content));
                        sendMessage(Contact.TEXT, msgModel, uuid);
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    ChatMsgEntity entity = new ChatMsgEntity();
                    entity.setMsgModel(msgModel);
                    entity.setUuid(uuid);
                    entity.setDate(getDate());
                    entity.setName(sendName);
                    entity.setMsgType(false);
                    entity.setText(content);
                    entity.setIsreceipt(isreceipt);
                    entity.setType(Contact.TEXT + "");
                    mDataArrays.add(entity);
                    mEditTextContent.setText("");
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(mListView.getCount() - 1);
                    mEditTextContent.requestFocus(); // 请求获取焦点
                    mEditTextContent.clearFocus();
                }
                else {
                    Toast.makeText(this, "发送内容不能为空", Toast.LENGTH_LONG).show();
                }
                
                break;
            case R.id.chatting_voice_btn:
                voiceBtn.setVisibility(View.GONE);
                keyboardBtn.setVisibility(View.VISIBLE);
                biaoqingfocuseBtn.setVisibility(View.GONE);
                viewPager.setVisibility(View.GONE);
                page_select.setVisibility(View.GONE);
                ll_fasong.setVisibility(View.GONE);
                ll_yuyin.setVisibility(View.VISIBLE);
                biaoqingBtn.setVisibility(View.GONE);
                plusGV.setVisibility(View.GONE);
                softkeybroadview = getWindow().peekDecorView();
                if (softkeybroadview != null) {
                    InputMethodManager inputmanger = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(softkeybroadview.getWindowToken(), 0);
                }
                break;
            case R.id.chatting_keyboard_btn:
                voiceBtn.setVisibility(View.VISIBLE);
                keyboardBtn.setVisibility(View.GONE);
                ll_fasong.setVisibility(View.VISIBLE);
                ll_yuyin.setVisibility(View.GONE);
                biaoqingBtn.setVisibility(View.VISIBLE);
                plusGV.setVisibility(View.GONE);
                break;
            case R.id.chatting_biaoqing_btn:
                biaoqingBtn.setVisibility(View.GONE);
                biaoqingfocuseBtn.setVisibility(View.VISIBLE);
                viewPager.setVisibility(View.VISIBLE);
                page_select.setVisibility(View.VISIBLE);
                plusGV.setVisibility(View.GONE);
                
                break;
            case R.id.chatting_biaoqing_focuse_btn:
                biaoqingBtn.setVisibility(View.VISIBLE);
                biaoqingfocuseBtn.setVisibility(View.GONE);
                viewPager.setVisibility(View.GONE);
                page_select.setVisibility(View.GONE);
                plusGV.setVisibility(View.GONE);
                break;
            case R.id.chatting_plus_focuse_btn:
                voiceBtn.setVisibility(View.VISIBLE);
                biaoqingBtn.setVisibility(View.VISIBLE);
                keyboardBtn.setVisibility(View.GONE);
                ll_fasong.setVisibility(View.VISIBLE);
                ll_yuyin.setVisibility(View.GONE);
                biaoqingfocuseBtn.setVisibility(View.GONE);
                viewPager.setVisibility(View.GONE);
                page_select.setVisibility(View.GONE);
                
                plusBtn.setVisibility(View.VISIBLE);
                
                softkeybroadview = getWindow().peekDecorView();
                if (softkeybroadview != null) {
                    InputMethodManager inputmanger = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(softkeybroadview.getWindowToken(), 0);
                }
                
                if (plusGV.getVisibility() == View.GONE) {
                    plusGV.setVisibility(View.VISIBLE);
                    plusAdapter = new PlusAdpter(this);
                    plusGV.setAdapter(plusAdapter);
                    plusGV.setOnItemClickListener(plusItemClickListener);
                }
                else {
                    plusGV.setVisibility(View.GONE);
                }
                
                break;
            
            case R.id.btn_yuyin:
                
                break;
        }
        
    }
    
    class GuidePageChangeListener implements OnPageChangeListener {
        
        @Override
        public void onPageScrollStateChanged(int arg0) {
            
        }
        
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
        
        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    page0.setImageDrawable(getResources().getDrawable(R.drawable.page_focused));
                    page1.setImageDrawable(getResources().getDrawable(R.drawable.page_unfocused));
                    
                    break;
                case 1:
                    page1.setImageDrawable(getResources().getDrawable(R.drawable.page_focused));
                    page0.setImageDrawable(getResources().getDrawable(R.drawable.page_unfocused));
                    page2.setImageDrawable(getResources().getDrawable(R.drawable.page_unfocused));
                    List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
                    for (int i = 0; i < 24; i++) {
                        Map<String, Object> listItem = new HashMap<String, Object>();
                        listItem.put("image", expressionImages1[i]);
                        listItems.add(listItem);
                    }
                    
                    SimpleAdapter simpleAdapter =
                        new SimpleAdapter(ChatActivity.this, listItems, R.layout.singleexpression,
                            new String[] {"image"}, new int[] {R.id.image});
                    gView2.setAdapter(simpleAdapter);
                    gView2.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                            Bitmap bitmap = null;
                            bitmap =
                                BitmapFactory.decodeResource(getResources(), expressionImages1[arg2
                                    % expressionImages1.length]);
                            ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);
                            SpannableString spannableString =
                                new SpannableString(expressionImageNames1[arg2].substring(1,
                                    expressionImageNames1[arg2].length() - 1));
                            spannableString.setSpan(imageSpan,
                                0,
                                expressionImageNames1[arg2].length() - 2,
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            mEditTextContent.append(spannableString);
                        }
                    });
                    break;
                case 2:
                    page2.setImageDrawable(getResources().getDrawable(R.drawable.page_focused));
                    page1.setImageDrawable(getResources().getDrawable(R.drawable.page_unfocused));
                    page0.setImageDrawable(getResources().getDrawable(R.drawable.page_unfocused));
                    List<Map<String, Object>> listItems1 = new ArrayList<Map<String, Object>>();
                    for (int i = 0; i < 24; i++) {
                        Map<String, Object> listItem = new HashMap<String, Object>();
                        listItem.put("image", expressionImages2[i]);
                        listItems1.add(listItem);
                    }
                    
                    SimpleAdapter simpleAdapter1 =
                        new SimpleAdapter(ChatActivity.this, listItems1, R.layout.singleexpression,
                            new String[] {"image"}, new int[] {R.id.image});
                    gView3.setAdapter(simpleAdapter1);
                    gView3.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                            Bitmap bitmap = null;
                            bitmap =
                                BitmapFactory.decodeResource(getResources(), expressionImages2[arg2
                                    % expressionImages2.length]);
                            ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);
                            SpannableString spannableString =
                                new SpannableString(expressionImageNames2[arg2].substring(1,
                                    expressionImageNames2[arg2].length() - 1));
                            spannableString.setSpan(imageSpan,
                                0,
                                expressionImageNames2[arg2].length() - 2,
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            mEditTextContent.append(spannableString);
                        }
                    });
                    break;
            }
        }
    }
    
    private void sendMessage(int type, MsgModel msgModel, String uuid) {
        if (MainApp.isIMConnecteStatus != 2) {
            msgModel.setStatus("3");
            msgService.updateStatus("3", msgModel.getUuid());
            Util.showMsg(this, "帐号未登录，请登录后重试....");
            return;
        }
        
        Util.showMsg(this, "消息发送中");
        //msgModel.setStatus("1");
        if ("0".equals(msgModel.getIsGroup())) {
            sendMessage(type, receContactUser.getImUserName(), msgModel, uuid);
        }
        else {
            sendMessage(type, receID, msgModel, uuid);
        }
    }
    
    /**
     * 单聊
     * 
     * @param type 1:文字；2：图片；3：语音；4：定位
     * @param content
     * 
     */
    private void sendMessage(int type, String toUser, MsgModel msgModel, final String uuid) {
        int chatType =
            "0".equals(msgModel.getIsGroup()) ? MessageConstants.Conversation.TYPE_SINGLE
                : MessageConstants.Conversation.TYPE_GROUP;
        
        CMMessage message = null;
        if (type == Contact.TEXT) {
            message = new CMMessage(chatType, toUser, new TextMessageBody(msgModel.getContent()));
        }
        else if (type == Contact.PHOTO) {
            File file = new File(msgModel.getFileName());
            if (file.exists()) {
                message = new CMMessage(chatType, toUser, new ImageMessageBody(file));
                
            }
            
        }
        else if (type == Contact.POSMAP) {
            message =
                new CMMessage(chatType, toUser, new LocationMessageBody(Double.valueOf(msgModel.getLatitude()),
                    Double.valueOf(msgModel.getLongitude()), msgModel.getContent(), new File(msgModel.getFileName())));
        }
        else if (type == Contact.REDIO) {
            message =
                new CMMessage(chatType, toUser, new AudioMessageBody(new File(msgModel.getFileName()),
                    Integer.valueOf(msgModel.getSecond())));
        }
        message.setUuid(uuid);
        CMCallBack callBack = new CMCallBack() {
            
            @Override
            public void onSuccess(CMMessage arg0) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("uuid", uuid);
                bundle.putLong("guid", arg0.getGuid());
                if (arg0.getContentType() == MessageConstants.Message.TYPE_PIC) {
                    
                    bundle.putString("file", ((ImageMessageBody)arg0.getMessageBody()).getOriginalUri());
                    
                }
                else if (arg0.getContentType() == MessageConstants.Message.TYPE_LOCATION) {
                    bundle.putString("file", ((LocationMessageBody)arg0.getMessageBody()).getOriginalUri());
                }
                else if (arg0.getContentType() == MessageConstants.Message.TYPE_AUDIO) {
                    bundle.putString("file", ((AudioMessageBody)arg0.getMessageBody()).getOriginalUri());
                }
                message.setData(bundle);
                message.what = 1;
                handler.sendMessage(message);
                
            }
            
            @Override
            public void onProgress(CMMessage arg0, int arg1) {
                
            }
            
            @Override
            public void onError(CMMessage arg0, String arg1) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("uuid", uuid);
                message.setData(bundle);
                message.what = 2;
                handler.sendMessage(message);
                
            }
        };
        
        CMIMHelper.getCmMessageManager().sendMessage(message, callBack);
        
    }
    
    public List<ChatMsgEntity> getMDataArrays() {
        return mDataArrays;
    }
    
    public EditText getMEditTextContent() {
        return mEditTextContent;
    }
    
    public ViewPager getViewPager() {
        return viewPager;
    }
    
    public LinearLayout getpage_select() {
        return page_select;
    }
    
    public ChatMsgViewAdapter getMAdapter() {
        return mAdapter;
    }
    
    public ListView getMListView() {
        return mListView;
    }
    
    // 查看群组成员
    public void doGroupUser(View view) {
        List<CMMember> cmMembers = CMIMHelper.getCmGroupManager().getGroupMembersfromServer(groupId);
        LoginConfig config = LoginConfigUtil.getConfig(this);
        if (NullUtils.isNotEmpty(cmMembers) && config.getImUserName().equals(cmMembers.get(0).getMemberId())) {
            Intent intent = new Intent(this, ChatAddGroupActivity.class);
            intent.putExtra("groupID", groupId);
            intent.putExtra("groupName", groupName);
            startActivityForResult(intent, 34567);
        }
        else {
            Intent intent = new Intent(this, ChatDetailGroupActivity.class);
            intent.putExtra("groupID", groupId);
            intent.putExtra("groupName", groupName);
            startActivity(intent);
        }
    }
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.im.message")) {
                MsgModel msgModel = (MsgModel)intent.getSerializableExtra("data");
                String groupId = msgModel.getGroupId();
                if (NullUtils.isNotEmpty(groupId)) {
                    // 群组聊天
                    // 发送人是当前页面人员则加载消息内容
                    if (msgModel.getGroupId().equals(receID)) {
                        // 未读条数清零
                        new MsgServiceImpl(context).clearIMNumbers(sendID, receID);
                        
                        ChatMsgEntity entity = new ChatMsgEntity();
                        entity.setMsgModel(msgModel);
                        entity.setUuid(msgModel.getUuid());
                        entity.setRecId(msgModel.getSendUserId());
                        entity.setSendUserId(msgModel.getRecId());
                        entity.setDate(msgModel.getSendDate());
                        entity.setName(receName);
                        entity.setMsgType(true);
                        entity.setText(msgModel.getContent());
                        entity.setIsreceipt(msgModel.getIsreceipt());
                        // 判断发送的类型
                        if (Contact.TEXT == Integer.valueOf((msgModel.getConType()))) {
                            // 文字内容
                            entity.setText(msgModel.getContent());
                            entity.setType(Contact.TEXT + "");
                        }
                        else if (Contact.PHOTO == Integer.valueOf(msgModel.getConType())) {
                            entity.setText(msgModel.getContent());
                            entity.setFileName(msgModel.getFileName());
                            entity.setType(Contact.PHOTO + "");
                        }
                        else if (Contact.REDIO == Integer.valueOf(msgModel.getConType())) {
                            // 声音
                            msgModel.setText("");
                            Bitmap bitmap = null;
                            Drawable d = context.getResources().getDrawable(R.drawable.other_dis_read); // xxx根据自己的情况获取drawable
                            BitmapDrawable bd = (BitmapDrawable)d;
                            bitmap = bd.getBitmap();
                            ImageSpan imageSpan = new ImageSpan(context, bitmap);
                            String yy_str = "a  " + GetTimeLength.getTimeLength(msgModel.getSecond());
                            spannablepic = new SpannableString(yy_str);
                            spannablepic.setSpan(new ForegroundColorSpan(Color.WHITE),
                                3,
                                yy_str.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannablepic.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
                                3,
                                yy_str.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannablepic.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            msgModel.setSpStr(spannablepic);
                            // 声音
                            entity.setFileName(msgModel.getFileName());
                            entity.setSpStr(spannablepic);
                            entity.setText("");
                            entity.setType(Contact.REDIO + "");
                        }
                        else if (Contact.POSMAP == Integer.valueOf(msgModel.getConType())) {
                            // 位置
                            entity.setFileName(msgModel.getFileName());
                            entity.setType(Contact.POSMAP + "");
                        }
                        
                        mDataArrays.add(entity);
                        mAdapter.notifyDataSetChanged();
                        mListView.setSelection(mListView.getCount() - 1);
                    }
                }
                else {
                    // 单人聊天
                    // 发送人是当前页面人员则加载消息内容
                    if (msgModel.getSendUserId().equals(receID)) {
                        // 未读条数清零
                        new MsgServiceImpl(context).clearIMNumbers(sendID, receID);
                        ChatMsgEntity entity = new ChatMsgEntity();
                        entity.setMsgModel(msgModel);
                        entity.setUuid(msgModel.getUuid());
                        entity.setRecId(msgModel.getSendUserId());
                        entity.setSendUserId(msgModel.getRecId());
                        entity.setDate(getDate());
                        entity.setName(receName);
                        entity.setMsgType(true);
                        entity.setText(msgModel.getContent());
                        entity.setIsreceipt("1");
                        // 判断发送的类型
                        if (Contact.TEXT == Integer.valueOf((msgModel.getConType()))) {
                            // 文字内容
                            // entity.setText(msgModel.getText());
                            // msgModel.setText(msgModel.getContent());
                            entity.setType(Contact.TEXT + "");
                        }
                        else if (Contact.PHOTO == Integer.valueOf(msgModel.getConType())) {
                            /*
                             * byte[] b = ByteToString.hexStringToByte(msgModel .getContent());
                             */
                            Resources res = getResources();
                            Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.default_avatar_big);
                            // 图片
                            ImageSpan imageSpan = new ImageSpan(context, bmp);
                            SpannableString spannablepic = new SpannableString("[smile]");
                            spannablepic.setSpan(imageSpan, 0, "[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            msgModel.setSpStr(spannablepic);
                            
                            msgModel.setText("");
                            entity.setSpStr(msgModel.getSpStr());
                            entity.setText("");
                            entity.setType(Contact.PHOTO + "");
                        }
                        else if (Contact.REDIO == Integer.valueOf(msgModel.getConType())) {
                            // 声音
                            msgModel.setFileName(msgModel.getContent());
                            msgModel.setText("");
                            Bitmap bitmap = null;
                            Drawable d = context.getResources().getDrawable(R.drawable.other_dis_read); // xxx根据自己的情况获取drawable
                            BitmapDrawable bd = (BitmapDrawable)d;
                            bitmap = bd.getBitmap();
                            ImageSpan imageSpan = new ImageSpan(context, bitmap);
                            String yy_str = "a  " + GetTimeLength.getTimeLength(msgModel.getSecond());
                            spannablepic = new SpannableString(yy_str);
                            spannablepic.setSpan(new ForegroundColorSpan(Color.WHITE),
                                3,
                                yy_str.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannablepic.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
                                3,
                                yy_str.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannablepic.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            msgModel.setSpStr(spannablepic);
                            msgModel.setText("");
                            // 声音
                            entity.setFileName(msgModel.getFileName());
                            entity.setSpStr(msgModel.getSpStr());
                            entity.setText("");
                            entity.setType(Contact.REDIO + "");
                        }
                        else if (Contact.POSMAP == Integer.valueOf(msgModel.getConType())) {
                            // 位置
                            entity.setType(Contact.POSMAP + "");
                        }
                        
                        mDataArrays.add(entity);
                        mAdapter.notifyDataSetChanged();
                        mListView.setSelection(mListView.getCount() - 1);
                        
                    }
                    
                }
                
            }
            else if (intent.getAction().equals("com.im.messageresver")) {
                
                String uuid = intent.getStringExtra("uuid");
                int index = 0;
                ChatMsgEntity chatMsgEntity = null;
                for (int i = (mDataArrays.size() - 1); i >= 0; i--) {
                    chatMsgEntity = mDataArrays.get(i);
                    if (chatMsgEntity.getUuid().equals(uuid)) {
                        index = i;
                        break;
                        
                    }
                }
                for (int i = 0; i <= index; i++) {
                    mDataArrays.get(i).setIsreceipt("1");
                }
                mAdapter.notifyDataSetChanged();
            }
            else if (intent.getAction().equals("com.im.delmessage")) {
                MsgModel model = (MsgModel)intent.getSerializableExtra(MsgTextLongClickListener.SER_KEY);
                int i = 0;
                for (ChatMsgEntity chatMsgEntity : mDataArrays) {
                    
                    if (model.getUuid().equals(chatMsgEntity.getMsgModel().getUuid())) {
                        mDataArrays.remove(chatMsgEntity);
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                    i++;
                }
                if (mDataArrays.size() > 0) {
                    if (i < mDataArrays.size()) {
                        mListView.setSelection(i);
                    }
                }
            }
            else if (intent.getAction().equals("com.im.sendpos")) {
                // Intent mIntent = new Intent("com.im.sendpos");
                // mIntent.putExtra("address", myaddress);
                // mIntent.putExtra("latitude",
                // String.valueOf(locPoint.latitude));
                // mIntent.putExtra("longitude",
                // String.valueOf(locPoint.longitude));
                // mIntent.putExtra("uuid", getIntent()
                // .getStringExtra("uuid"));
                // Photo.saveBitmap(
                // getIntent().getStringExtra("uuid"),
                // Photo.zoomImg(arg0, 128,
                // PosLocation.this));
                MsgModel msgModel = new MsgModel();
                msgModel.setUuid(intent.getStringExtra("uuid"));
                msgModel.setContent(intent.getStringExtra("address"));
                msgModel.setFileName(Photo.getSaveIMPicPath() + msgModel.getUuid() + ".png");
                msgModel.setLatitude(intent.getStringExtra("latitude"));
                msgModel.setLongitude(intent.getStringExtra("longitude"));
                // 地图
                msgModel.setConType(Contact.POSMAP + "");
                msgModel.setRecId(receID);
                msgModel.setRecName(receName);
                msgModel.setSendDate(getDate());
                msgModel.setSendUserId(sendID);
                msgModel.setSendUserName(sendName);
                if (type > 1 ? true : false) {
                    msgModel.setIsGroup("1");
                }
                else {
                    msgModel.setIsGroup("0");// 个人聊天
                }
                if (type > 1) {
                    msgModel.setGroupId(groupId);
                    msgModel.setGroupName(groupName);
                }
                msgModel.setStatus("1");// 消息状态 正在发送
                msgModel.setIsreceipt("0");
                msgService.saveIM(msgModel);
                sendMessage(Contact.POSMAP, msgModel, msgModel.getUuid());
                ChatMsgEntity entity = new ChatMsgEntity();
                entity.setMsgModel(msgModel);
                entity.setUuid(msgModel.getUuid());
                entity.setDate(getDate());
                entity.setName(sendName);
                entity.setMsgType(false);
                entity.setText("");
                entity.setType(Contact.POSMAP + "");
                entity.setFileName(msgModel.getFileName());
                entity.setIsreceipt(isreceipt);
                mDataArrays.add(entity);
                mAdapter.notifyDataSetChanged();
            }
            
        }
    };
    
    private BroadcastReceiver chatnavreceiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.im.chatnavreceiver")) {
                if (intent.getStringExtra("chatnav") != null) {
                    if (intent.getStringExtra("chatnav").toString().equals("del")) {
                        mAdapter.notifyDataSetChanged();
                        if (intent.getStringExtra("chatnum") != null) {
                            if (Integer.parseInt(intent.getStringExtra("chatnum")) > 1) {
                                mListView.setSelection(Integer.parseInt(intent.getStringExtra("chatnum")) - 1);
                            }
                            else {
                                mListView.setSelection(0);
                            }
                            
                        }
                        
                    }
                }
                
            }
        }
    };
    
    /**
     * 发送图片
     */
    private void SendPhoto(String uuid) {
        
        try {
            
            voiceBtn.setVisibility(View.VISIBLE);
            biaoqingBtn.setVisibility(View.VISIBLE);
            keyboardBtn.setVisibility(View.GONE);
            ll_fasong.setVisibility(View.VISIBLE);
            ll_yuyin.setVisibility(View.GONE);
            biaoqingfocuseBtn.setVisibility(View.GONE);
            viewPager.setVisibility(View.GONE);
            page_select.setVisibility(View.GONE);
            plusGV.setVisibility(View.GONE);
            
            // 发送文本
            String photoContent = Photo.getSaveIMPicPath() + uuid + ".png";
            MsgModel msgModel = new MsgModel();
            msgModel.setUuid(uuid);
            msgModel.setContent("");
            // 图片
            msgModel.setConType(Contact.PHOTO + "");
            msgModel.setRecId(receID);
            msgModel.setRecName(receName);
            msgModel.setSendDate(getDate());
            msgModel.setSendUserId(sendID);
            msgModel.setSendUserName(this.sendName);
            msgModel.setIsreceipt(isreceipt);
            msgModel.setFileName(photoContent);
            if (this.isGroup) {
                msgModel.setIsGroup("1");
            }
            else {
                msgModel.setIsGroup("0");// 个人聊天
            }
            if (type > 1) {
                msgModel.setGroupId(groupId);
                msgModel.setGroupName(groupName);
            }
            
            msgService.saveIM(msgModel);
            ChatMsgEntity entity = new ChatMsgEntity();
            entity.setMsgModel(msgModel);
            entity.setUuid(uuid);
            entity.setType(Contact.PHOTO + "");
            entity.setDate(getDate());
            entity.setName(sendName);
            entity.setMsgType(false);
            entity.setIsreceipt(isreceipt);
            entity.setFileName(photoContent);
            mDataArrays.add(entity);
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(mListView.getCount() - 1);
            mEditTextContent.requestFocus(); // 请求获取焦点
            mEditTextContent.clearFocus();
            sendMessage(Contact.PHOTO, msgModel, uuid);
            
        }
        catch (Exception e) {
            e.printStackTrace();
            // Toast.makeText(context, "发送图片失败", Toast.LENGTH_SHORT).show();
        }
        
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {

            	 try {
                     Bitmap bitmapTemp = Photo.getThumbnail(photoUri, 0, ChatActivity.this);
//                     String uuid = UUID.randomUUID().toString();
                     if (bitmapTemp != null) {
                         Photo.saveBitmap(photoUUid, zoomImg(bitmapTemp, 0));
                         File oldFile = new File(Photo.getSaveIMPicPath(),  photoUUid+ ".jpg");
                         if(oldFile.exists()) {
                        	 oldFile.delete();
                         }
                         Bitmap imageBt = zoomImg(bitmapTemp, 128);
                         ImageSpan imageSpan = new ImageSpan(ChatActivity.this, imageBt);
                         SpannableString spannable =
                             new SpannableString(mEditTextContent.getText().toString() + "[smile]");
                         spannable.setSpan(imageSpan, mEditTextContent.getText().length(), mEditTextContent.getText()
                             .length() + "[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                         sendPicDialog(photoUUid);
                     }
                     
                 }
                 catch (Exception e1) {
                     e1.printStackTrace();
                     return;
                 }
            }
            else if (requestCode == 2) {
                try {
                    ContentResolver resolver = getContentResolver();
                    Uri originalUri = data.getData(); // 获得图片的uri
                    /*
                     * String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(originalUri, proj,
                     * null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore
                     * .Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(column_index);
                     */
                    
                    // Bitmap bitmapTemp =
                    // MediaStore.Images.Media.getBitmap(resolver, originalUri);
                    Bitmap bitmapTemp = Photo.getThumbnail(originalUri, 0, ChatActivity.this);
                    String uuid = UUID.randomUUID().toString();
                    if (bitmapTemp != null) {
                        Photo.saveBitmap(uuid, zoomImg(bitmapTemp, 0));
                        
                        // Bitmap imageBitmap =
                        // BitmapFactory.decodeFile(Photo.getSaveIMPicPath()+uuid
                        // + ".png");
                        Bitmap imageBt = zoomImg(bitmapTemp, 128);
                        ImageSpan imageSpan = new ImageSpan(ChatActivity.this, imageBt);
                        SpannableString spannable =
                            new SpannableString(mEditTextContent.getText().toString() + "[smile]");
                        spannable.setSpan(imageSpan, mEditTextContent.getText().length(), mEditTextContent.getText()
                            .length() + "[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        sendPicDialog(uuid);
                    }
                    
                }
                catch (Exception e1) {
                    e1.printStackTrace();
                    return;
                }
                
            }else if(requestCode==34567&&resultCode==RESULT_OK){
                TextView textView = (TextView)findViewById(R.id.tvtest);
                textView.setText(data.getStringExtra("groupName"));
                
            }
        }
        else {
            return;
        }
        
    }
    private void sendPicDialog(final String uuid){
        new Builder(this).setTitle("操作提示").setMessage("确定发送图片").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                SendPhoto(uuid);
                arg0.dismiss();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
            }
        }).setCancelable(false).show();
    }
    
    private Handler handler = new Handler() {
        
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String fileName = "";
                if (msg.getData().containsKey("file")) {
                    fileName = msg.getData().getString("file");
                }
                msgService.updateMessage(fileName,
                    msg.getData().getLong("guid", 0) + "",
                    msg.getData().getString("uuid"));
                Util.showMsg(ChatActivity.this, "消息发送成功");
                Intent mIntent = new Intent("com.im.sendmessage");
                context.sendBroadcast(mIntent);
            }
            else if (msg.what == 2) {
                for (ChatMsgEntity chatMsgEntity : mDataArrays) {
                    if (chatMsgEntity.getUuid().equals(msg.getData().getString("uuid"))) {
                        chatMsgEntity.getMsgModel().setStatus("3");
                        break;
                    }
                    
                }
                mAdapter.notifyDataSetChanged();
                msgService.updateStatus("3", msg.getData().getString("uuid"));
                Util.showMsg(ChatActivity.this, "消息发送失败");
            }
        }
        
    };
    
    /*
     * private void findFriendStatus(String phone) { String url = UrlConstant.LOCAL_URI + "findFriendStatus?phone=" +
     * phone; aq.progress(0).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
     * 
     * public void callback(String url, JSONObject json, AjaxStatus status) { // TODO Auto-generated method stub //
     * super.callback(url, object, status); if (json != null) { try { aq.id(R.id.tvstutas) .text(json.getString("msg"));
     * } catch (Exception e) { aq.id(R.id.tvstutas).text("离线"); } } else { aq.id(R.id.tvstutas).text("离线"); } }
     * 
     * });
     * 
     * }
     */
    
    // 缩放图片
    public Bitmap zoomImg(Bitmap bm, int w) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        
        DisplayMetrics dm = new DisplayMetrics();
        dm = this.getApplicationContext().getResources().getDisplayMetrics();
        int newWidth = 0;
        if (w == 0) {
            newWidth = dm.widthPixels;
        }
        else {
            newWidth = w;
        }
        
        // 计算缩放比例
        float scaleWidth = ((float)newWidth) / width;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }
    
    private void showCreateConferenceConfirmDialog() {
        if (conferenceConfirmDialog == null) {
            conferenceConfirmDialog =
                DialogFactory.getConfirmDialog2(this,
                    "发起语音会议",
                    getString(R.string.confirm_create_conference),
                    getString(R.string.cancel),
                    getString(R.string.ok),
                    null,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    createConference();
                                }
                            }, 0);
                            
                        }
                    });
        }
        if (!conferenceConfirmDialog.isShowing()) {
            conferenceConfirmDialog.show();
        }
    }
    
    private void createConference() {
        StringBuffer member_tels = new StringBuffer();
        StringBuffer sbMembers = new StringBuffer();
        
        List<CMMember> cmMembers = CMIMHelper.getCmGroupManager().getGroupMembersfromServer(groupId);
        if (NullUtils.isEmpty(cmMembers)) {
            Toast.makeText(this, "获取群成员失败!", Toast.LENGTH_LONG).show();
            return;
        }
        
        for (CMMember tem : cmMembers) {// 若群中成员包含本账号会查不到，在会议创建界面会将创建者账号的手机号传上去
            String member = tem.getMemberId();
            if (TextUtils.isEmpty(member))
                continue;
            ContactsUser contactsUser = contactUserServiceImpl.findOnlineContactsUserByIMUserName(member);
            if (contactsUser == null) { // 不是本地好友 从网上获取
                continue;
            }
            
            if (!isIncluded(member_tels, contactsUser.getTelPhone())) { // getPhoneNumber()
                member_tels.append(contactsUser.getTelPhone() + "|"); // getPhoneNumber()
                sbMembers.append(member + ",");
            }
            // member_tels = member_tels + _group_user.getPhoneNumber() +
            // CMChatConfig.appKey + "|";
        }
        if (member_tels.toString().trim().length() == 0 || member_tels.toString().split("\\|").length <= 0) {
            Toast.makeText(this, "至少1位除自己以外的群成员!", Toast.LENGTH_LONG).show();
            return;
        }
        String groupName = CMIMHelper.getCmGroupManager().getGroupNamefromServer(groupId);
        if (groupName != null) {
            if (groupName.length() > 15) {
                groupName = groupName.substring(0, 15);
            }
        }
        else {
            groupName = "";
        }
    }
    
    /**
     * 重发
     */
    public OnClickListener SendItem = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            ChatMsgEntity entity = (ChatMsgEntity)v.getTag();
            if(Util.isConnect(context) && MainApp.isIMConnecteStatus == 2){
                sendMessage(Integer.parseInt(entity.getType()), entity.getMsgModel(), entity.getUuid());
                /*if (MainApp.isIMConnecteStatus != 2) {
                entity.getMsgModel().setStatus("2");
                }*/
                entity.getMsgModel().setStatus("1");
                mAdapter.notifyDataSetChanged();
            }
            
        }
            
    };

    /**
     * 
     * @方法名：isIncluded
     * @描述：(电话号码是否已包含)
     * @return
     * @输出：boolean
     * @作者：CB
     * 
     */
    private boolean isIncluded(StringBuffer member_tels, String number) {
        boolean result = false;
        String[] _member_tels_list = member_tels.toString().split("\\|");
        for (String _number : _member_tels_list) {
            if (TextUtils.isEmpty(_number))
                continue;
            if (_number.equals(number)) {
                result = true;
                break;
            }
        }
        
        return result;
    }
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        unregisterReceiver(chatnavreceiver);
        super.onDestroy();
    }
    
}
